package com.bigknow.appstore.web.framework.util;

import com.bigknow.appstore.web.base.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by Administrator on 2015/5/6.
 */
@Component
public final class AuthenticateUserUtil {

    @Autowired
    private Datastore ds;

    private static AuthenticateUserUtil au;

    @PostConstruct
    public void init() {
        au = this;
    }

    public static String getUserId() {
        User user;
        if ((user = getUser()) != null) {
            return user.getId();
        } else {
            return null;
        }
    }

    public static User getUser() {
        Subject subject = SecurityUtils.getSubject();
        if (subject == null) {
            return null;
        }
        return (User) subject.getPrincipal();
    }

    public static boolean isSysAdmin(User user) {
        String[] roles = user.getRoleIds().split(",");
        for (String role : roles) {
            if (role.equals("1")) return true;
        }
        return false;
    }

    public static boolean isCurrentUserIsSysAdmin(){
        return isSysAdmin(getUser());
    }

    public Datastore getDs() {
        return ds;
    }

    public void setDs(Datastore ds) {
        this.ds = ds;
    }
}
